<template>
  <el-card ref="wrapper" :body-style="{ padding: 0 }">
    <div style="height: 600px;">
      <v-stage
        :config="stageConfig"
        @mousedown="mousedownHandler"
        @mouseup="mouseupHandler"
        @mousemove="mousemoveHandler"
      >
        <v-layer>
          <v-line
            v-for="(line,index) in lines"
            :key="index"
            :config="line"
          />
        </v-layer>
      </v-stage>
    </div>
  </el-card>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      stroke: '#df4b26',
      strokeWidth: 5,
      start: false,
      stageConfig: {
        width: 800,
        height: 700
      }
    }
  },

  computed: {
    ...mapState(['lines', 'holder', 'nickname'])
  },

  mounted() {
    this.stageConfig.width = this.$refs.wrapper.$el.offsetWidth
  },

  methods: {
    mousemoveHandler(e) {
      if (this.start) {
        let line = this.lines[this.lines.length - 1].points
        line = line.concat([e.evt.layerX, e.evt.layerY])
        this.$store.dispatch('updateLine', line)
      }
    },
    mousedownHandler(e) {
      if (this.holder && this.holder === this.nickname) {
        this.start = true
        const line = { stroke: this.stroke, strokeWidth: this.strokeWidth, points: [e.evt.layerX, e.evt.layerY] }
        this.$store.dispatch('drawLine', line)
      }
    },
    mouseupHandler() {
      this.start = false
    }
  }
}
</script>
